<template>
  <view :data-theme="globPrimary">
    <u-navbar title="成为机构"
      ><view class="navbar-btn" slot="right" v-if="step" @click="nextStep">上一步</view></u-navbar
    >
    <view class="teacher-wrapper">
      <view class="teacher-view">
        <u-cell-group :border="false">
          <view v-show="!step">
            <u-cell-item
              title="当前用户"
              :value="userInfo.nick_name"
              :arrow="false"
              hover-class="none"
              :value-style="{
                color: '#606266',
              }"
              label="*该帐号将成为机构管理员"
            ></u-cell-item>
            <u-cell-item
              title="认证状态"
              :value="authStatusText"
              :arrow="false"
              :border-bottom="false"
              hover-class="none"
              :value-style="{
                color: '#B7BAC1',
              }"
            ></u-cell-item>
            <u-gap height="10" bg-color="#F7F7F7"></u-gap>
            <u-field
              v-model="form.title"
              label="机构名称"
              placeholder="请填写"
              input-align="right"
              :clearable="false"
              :maxlength="50"
              :placeholderStyle="'color: #B7BAC1'"
            ></u-field>
            <u-cell-item
              title="所属分类（行业）"
              value="请选择"
              :border-bottom="false"
              hover-class="none"
              @click="show = true"
            ></u-cell-item>
            <view class="u-border-bottom category">
              <view class="item" v-for="(item, index) in categorySelect" :key="index">
                <text class="text u-line-1">{{ item.title }}</text>
                <u-icon name="close" class="close" @click="deleteCategoryId(item.id)"></u-icon>
              </view>
            </view>
            <u-cell-item title="LOGO" :arrow="false" hover-class="none">
              <view slot="right-icon" class="avatar">
                <edu-upload
                  max-count="1"
                  :args="{
                    ...args,
                    width: '100rpx',
                    height: '100rpx',
                  }"
                  :value.sync="form.logo"
                  :soltType="'school'"
                >
                  <view slot="addBtn" class="slot-btn"><u-avatar size="100"></u-avatar></view>
                </edu-upload>
              </view>
            </u-cell-item>
            <u-field
              v-model="form.intro"
              label="机构简介"
              placeholder="请填写机构简介"
              type="textarea"
              :clearable="false"
              :maxlength="800"
              :placeholderStyle="'color: #B7BAC1'"
            ></u-field>
            <u-field
              v-model="form.telephone"
              label="联系电话"
              placeholder="请填写"
              input-align="right"
              :border-bottom="false"
              :clearable="false"
              :placeholderStyle="'color: #B7BAC1'"
            ></u-field>
          </view>
          <view v-show="step">
            <u-field
              v-model="form.address"
              label="联系地址"
              placeholder="请填写联系地址"
              type="textarea"
              :clearable="false"
              :maxlength="-1"
              :placeholderStyle="'color: #B7BAC1'"
            ></u-field>
            <u-field
              v-model="form.legal_IDcard"
              label="法人身份证号"
              placeholder="请填写"
              input-align="right"
              :clearable="false"
              label-width="170"
              :placeholderStyle="'color: #B7BAC1'"
            ></u-field>
            <u-cell-item
              title="身份证正反面"
              :arrow="false"
              :border-bottom="false"
              hover-class="none"
            ></u-cell-item>
            <view class="upload">
              <view class="item">
                <edu-upload
                  max-count="1"
                  :args="{
                    ...args,
                    imgsrc: '@/pageUser/static/images/id_front.png',
                  }"
                  :value.sync="form.legal_IDcard_positive"
                  :soltType="'teach'"
                >
                  <view slot="addBtn" class="slot-btn"
                    ><u-image
                      :width="args.width"
                      :height="args.height"
                      src="@/pageUser/static/images/id_front.png"
                    ></u-image
                  ></view>
                </edu-upload>
              </view>
              <view class="item">
                <edu-upload
                  max-count="1"
                  :args="{
                    ...args,
                    imgsrc: '@/pageUser/static/images/id_back_def.png',
                  }"
                  :value.sync="form.legal_IDcard_side"
                  :soltType="'teach'"
                >
                  <view slot="addBtn" class="slot-btn"
                    ><u-image
                      :width="args.width"
                      :height="args.height"
                      src="@/pageUser/static/images/id_back_def.png"
                    ></u-image
                  ></view>
                </edu-upload>
              </view>
            </view>
            <u-cell-item
              title="营业执照"
              :arrow="false"
              :border-bottom="false"
              hover-class="none"
            ></u-cell-item>
            <view class="upload">
              <view class="item">
                <edu-upload
                  max-count="1"
                  :args="{
                    ...args,
                    height: '338rpx',
                    imgsrc: '@/pageUser/static/images/zhizhao_img.png',
                  }"
                  :value.sync="form.business_license"
                  :soltType="'teach'"
                >
                  <view slot="addBtn" class="slot-btn"
                    ><u-image
                      width="338rpx"
                      height="338rpx"
                      src="@/pageUser/static/images/zhizhao_img.png"
                    ></u-image
                  ></view>
                </edu-upload>
              </view>
            </view>
          </view>
        </u-cell-group>
      </view>
      <view class="teacher-bottom" v-show="!step">
        <edu-button type="primary" @click="nextStep">下一步</edu-button>
      </view>
      <view class="teacher-bottom" v-show="step">
        <view class="agreement">
          <u-checkbox v-model="check" :activeColor="globPrimaryColor">我已阅读并同意</u-checkbox>
          <text
            :style="{ color: globPrimaryColor }"
            @click="
              $u.route('/pages/protocol', {
                key: 'schoolUser',
              })
            "
          >
            《{{ getAgreementTitle('schoolUser') }}》
          </text>
        </view>
        <edu-button type="primary" @click="submitForm">提交申请</edu-button>
      </view>
    </view>

    <u-popup v-model="show" mode="right" width="100%" :mask="false" close-icon-pos="top-left">
      <view :style="{ height: globStatusBarHeight + 'px', width: '100%' }"></view>
      <view class="category-header u-border-bottom" :style="[navbarStyle]">
        <u-icon @click="show = false" name="close" class="close"></u-icon>
        <view class="title">选择所属行业</view>
        <view class="btn" @click="confirm">确定</view>
      </view>
      <view
        class="category-wrap"
        :style="{
          height: globWindowHeight - globStatusBarHeight - 50 + 'px',
        }"
      >
        <scroll-view
          scroll-y
          scroll-with-animation
          class="tab-view menu-scroll-view"
          :scroll-top="scrollTop"
        >
          <view
            v-for="(item, index) in categoryList"
            :key="index"
            class="tab-item"
            :class="[current == index ? 'active' : '']"
            @tap.stop="swichMenu(index)"
          >
            <text class="u-line-2">{{ item.title }}</text>
          </view>
        </scroll-view>
        <block v-for="(item, index) in categoryList" :key="index">
          <view class="right-box" v-if="current == index">
            <scroll-view scroll-y>
              <view class="page-view">
                <view
                  class="class-title"
                  :class="[addCategoryClass(item.id) ? 'active' : '']"
                  @click="chooseCategoryId(item, index)"
                >
                  <text>全部</text>
                  <u-icon name="arrow-right"></u-icon>
                </view>
                <view class="class-item" v-for="(item1, index1) in item.child" :key="index1">
                  <view
                    class="item-title"
                    :class="[addCategoryClass(item1.id) ? 'active' : '']"
                    @click="chooseCategoryId(item1, index)"
                  >
                    <text class="u-line-1">{{ item1.title }}</text>
                    <u-icon name="arrow-right"></u-icon>
                  </view>
                  <view class="item-container">
                    <view class="thumb" v-for="(item2, index2) in item1.child" :key="index2">
                      <view
                        class="name u-line-1"
                        :class="[addCategoryClass(item2.id) ? 'active' : '']"
                        @click="chooseCategoryId(item2, index)"
                        >{{ item2.title }}</view
                      >
                    </view>
                  </view>
                </view>
              </view>
            </scroll-view>
          </view>
        </block>
      </view>
    </u-popup>
    <u-toast ref="uToast" />
  </view>
</template>

<script>
import { mapGetters } from 'vuex'
// 获取系统状态栏的高度
let menuButtonInfo = {}
// 如果是小程序，获取右上角胶囊的尺寸信息，避免导航栏右侧内容与胶囊重叠(支付宝小程序非本API，尚未兼容)
// #ifdef MP-WEIXIN || MP-BAIDU || MP-TOUTIAO || MP-QQ
menuButtonInfo = uni.getMenuButtonBoundingClientRect()
// #endif
export default {
  data() {
    return {
      args: {
        width: '338rpx',
        height: '213rpx',
        count: 1,
        customBtn: true,
      },
      check: false,
      show: false,
      current: 0,
      scrollTop: 0,
      menuHeight: 0, // 左边菜单的高度
      menuItemHeight: 0, // 左边菜单item的高度
      categoryList: [],
      categoryData: [],
      categoryQuery: [],
      categorySelect: [],
      authStatus: 0,
      authStatusText: '',
      form: {
        title: '',
        category: '',
        logo: 0,
        intro: '',
        telephone: '',
        address: '',
        legal_IDcard: '',
        legal_IDcard_positive: 0,
        legal_IDcard_side: 0,
        business_license: 0,
      },
      step: false,
    }
  },
  computed: {
    ...mapGetters({
      globPrimary: 'designSetting/getGlobTheme',
      globPrimaryColor: 'designSetting/getGlobThemeColor',
      globStatusBarHeight: 'projectSetting/globStatusBarHeight',
      globWindowHeight: 'projectSetting/globWindowHeight',
      userInfo: 'user/getUserInfo',
      getAgreementTitle: 'projectSetting/getAgreementTitle',
    }),
    navbarStyle() {
      let style = {}
      // // 如果是各家小程序，导航栏内部的宽度需要减少右边胶囊的宽度
      // #ifdef MP
      style.width = menuButtonInfo.left + 'px'
      // #endif
      return style
    },
  },
  mounted() {
    this.getData()
  },
  options: { styleIsolation: 'shared' },
  methods: {
    getData() {
      this.$edu.api.getSchoolAuth().then((res) => {
        const { data } = res
        this.authStatus = data.auth_status
        this.authStatusText = data.auth_status_text
        this.categoryList = data.category
      })
    },
    // 验证
    validate(callback) {
      if (this.$u.test.empty(this.form.title)) {
        this.$u.toast('机构名称不能为空')
        return false
      } else if (this.$u.test.empty(this.categorySelect)) {
        this.$u.toast('请至少选择一个行业')
        return false
      } else if (this.$u.test.empty(this.form.logo)) {
        this.$u.toast('请选择LOGO')
        return false
      } else if (this.$u.test.empty(this.form.intro)) {
        this.$u.toast('请输入简介')
        return false
      } else if (this.$u.test.empty(this.form.telephone)) {
        this.$u.toast('联系电话不能为空')
        return false
      } else if (!this.$u.test.mobile(this.form.telephone)) {
        this.$u.toast('请输入正确的联系电话')
        return false
      } else if (this.$u.test.empty(this.form.address)) {
        this.$u.toast('联系地址不能为空')
        return false
      } else if (this.$u.test.empty(this.form.legal_IDcard)) {
        this.$u.toast('身份证号码不能为空')
        return false
      } else if (!this.$u.test.idCard(this.form.legal_IDcard)) {
        this.$u.toast('请输入正确的身份证号码')
        return false
      } else if (this.$u.test.empty(this.form.legal_IDcard_positive)) {
        this.$u.toast('请选择身份证正面照')
        return false
      } else if (this.$u.test.empty(this.form.legal_IDcard_side)) {
        this.$u.toast('请选择身份证背面照')
        return false
      } else if (this.$u.test.empty(this.form.business_license)) {
        this.$u.toast('请选择营业执照')
        return false
      } else if (!this.check) {
        this.$u.toast('请先阅读协议并同意')
        return
      } else {
        callback()
      }
    },
    // 提交
    submitForm() {
      this.validate(() => {
        this.form.category = this.categoryParams() // 分类的id
        this.$edu.api
          .createSchoolAuth(this.form)
          .then((res) => {
            this.$refs.uToast.show({
              title: res.msg,
              callback: () => {
                this.$u.route({
                  type: 'back',
                })
              },
            })
          })
          .catch((err) => {
            this.$u.toast(err.msg)
          })
      })
    },
    // 下一步
    nextStep() {
      this.step = !this.step
    },
    // 点击左边的栏目切换
    async swichMenu(index) {
      if (index == this.current) return
      this.current = index
      // 如果为0，意味着尚未初始化
      if (this.menuHeight == 0 || this.menuItemHeight == 0) {
        await this.getElRect('menu-scroll-view', 'menuHeight')
        await this.getElRect('tab-item', 'menuItemHeight')
      }
      // 将菜单菜单活动item垂直居中
      this.scrollTop = index * this.menuItemHeight + this.menuItemHeight / 2 - this.menuHeight / 2
    },
    // 获取一个目标元素的高度
    getElRect(elClass, dataVal) {
      new Promise((resolve, reject) => {
        const query = uni.createSelectorQuery().in(this)
        query
          .select('.' + elClass)
          .fields({ size: true }, (res) => {
            // 如果节点尚未生成，res值为null，循环调用执行
            if (!res) {
              setTimeout(() => {
                this.getElRect(elClass)
              }, 10)
              return
            }
            this[dataVal] = res.height
          })
          .exec()
      })
    },
    // 分类选择
    chooseCategoryId(item, indexs) {
      var index = this.categoryData.findIndex((data) => data.id === item.id)
      if (index == -1) {
        this.categoryData.push({
          key: indexs,
          id: item.id,
          title: item.title,
        })
      } else {
        this.categoryData.splice(index, 1)
      }
    },
    categoryParams() {
      let list = this.categorySelect
      let data = []
      let newArr = []
      for (var i = 0; i < list.length; i++) {
        if (!data[list[i].key]) {
          var arr = []
          arr.push(list[i].id)
          data[list[i].key] = arr
        } else {
          data[list[i].key].push(list[i].id)
        }
      }
      // 去掉null
      data.forEach((item) => {
        if (item) {
          newArr.push(item)
        }
      })
      return newArr
    },
    confirm() {
      this.show = false
      this.categorySelect = this.categoryData
    },
    // 添加选中样式
    addCategoryClass(key) {
      var index = this.categoryData.findIndex((data) => data.id === key)
      if (index == -1) {
        return false
      } else {
        return true
      }
    },
    // 删除选择
    deleteCategoryId(id) {
      this.categorySelect.splice(
        this.categorySelect.findIndex((item) => item.id === id),
        1
      )
    },
  },
}
</script>

<style lang="scss" scoped>
.navbar-btn {
  font-size: 30rpx;
  font-weight: 400;
  color: $edu-main-color;
  margin-right: 30rpx;
}
/* #ifdef APP-PLUS */
/deep/.u-close {
  top: 50px !important;
}
/* #endif */
.teacher-wrapper {
  .teacher-view {
    padding-bottom: 20rpx;
    background-color: #ffffff;
    /deep/.u-cell {
      width: calc(100% - 30rpx);
      margin-left: 30rpx;
      padding-left: 0;
      .u-cell_title {
        color: $edu-main-color;
      }
      .u-cell__value {
        color: #b7bac1;
      }
      .u-cell__right-icon-wrap {
        color: #dcdfe6;
      }
    }
    .u-field {
      padding: 29rpx 32rpx;
    }
    .category {
      display: flex;
      flex-wrap: wrap;
      justify-content: flex-end;
      margin-left: 30rpx;
      padding-right: 30rpx;
      .item {
        display: flex;
        margin-left: 24rpx;
        margin-bottom: 32rpx;
        padding: 5rpx 10px;
        background: #f1f1f1;
        border-radius: 32px;
        font-weight: 400;
        color: $edu-content-color;
        .text {
          font-size: 26rpx;
          max-width: 240rpx;
        }
        .close {
          margin-left: 10rpx;
          font-size: 18rpx;
        }
      }
    }
    .upload {
      display: flex;
      flex-wrap: wrap;
      padding-left: 20rpx;
      .item {
        padding: 0 10rpx;
      }
      /deep/.u-list-item {
        margin: 0;
      }
    }
    .avatar {
      display: flex;
      border-radius: 100%;
      overflow: hidden;
      .u-avatar {
        display: flex;
      }
      /deep/.u-list-item {
        margin: 0;
      }
    }
  }
  .teacher-bottom {
    padding: 50rpx 30rpx 20rpx;
    .agreement {
      display: flex;
      align-items: center;
      margin-bottom: 90rpx;
      @include text-color();
      font-size: 28rpx;
      /deep/.u-checkbox__label {
        font-size: 28rpx;
        color: $u-tips-color;
        margin-right: 0;
      }
    }
  }
}

/* #ifdef MP-WEIXIN */
/deep/.u-close--top-left.data-v-4b631af3 {
  margin-top: 68rpx;
}
/* #endif */

.category-header {
  height: 100rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  .close {
    position: absolute;
    left: 30rpx;
    top: 30rpx;
  }
  .title {
    font-size: 36rpx;
    font-weight: 500;
    color: $edu-main-color;
  }
  .btn {
    font-size: 30rpx;
    font-weight: 400;
    color: $edu-main-color;
    position: absolute;
    right: 30rpx;
    top: 30rpx;
  }
}
.category-wrap {
  display: flex;
  overflow: hidden;
  background-color: #fff;
  .tab-view {
    width: 210rpx;
    height: 100%;
    background: #f7f7f7;
    .tab-item {
      height: 120rpx;
      padding-right: 10rpx;
      padding-left: 16rpx;
      background: #f7f7f7;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 28rpx;
      color: $edu-content-color;
      font-weight: 400;
      &.active {
        position: relative;
        color: $edu-main-color;
        background-color: #ffffff;
        &::before {
          content: '';
          position: absolute;
          border-left-width: 6rpx;
          border-left-style: solid;
          @include border-color();
          height: 120rpx;
          left: 0;
          top: 0;
        }
      }
    }
  }
  .right-box {
    width: calc(100vw - 210rpx);
  }
  .page-view {
    padding: 30rpx;
    background-color: #fff;
    .class-title {
      font-size: 30rpx;
      font-weight: 500;
      color: $edu-main-color;
      margin-bottom: 50rpx;
      &.active {
        @include text-color();
      }
    }
    .class-item {
      border-radius: 8rpx;
      .item-title {
        display: flex;
        font-size: 30rpx;
        font-weight: 500;
        color: $edu-main-color;
        margin-bottom: 30rpx;
        &.active {
          @include text-color();
        }
      }
      .item-container {
        display: flex;
        flex-wrap: wrap;
        margin-left: -14rpx;
        margin-right: -14rpx;
        .thumb {
          padding: 0 14rpx;
          margin-bottom: 40rpx;
        }
        .name {
          max-width: 480rpx;
          padding: 0 20rpx;
          height: 64rpx;
          line-height: 64rpx;
          text-align: center;
          background: #f7f7f7;
          border-radius: 32px;
          font-size: 28rpx;
          font-weight: 400;
          color: $u-main-color;
          &.active {
            @include text-color();
          }
        }
      }
    }
  }
}
</style>
